package com.lwl.Algorithmic_data_structure.链表;

/**
 * 使用数组实现队列
 */
public class Array_Queue {
    
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(5);
        queue.push(1);
        queue.push(2);
        queue.push(3);
        queue.push(4);
        queue.push(5);
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        queue.print();
    }
    
    public static class ArrayQueue{
        private int[] array;
        // 弹值下标
        private int popIndex;
        // 插值下标
        private int pushIndex;
        private int queueMaxSize;
        private int queueCurSize;

        public ArrayQueue(int size){
            array = new int[size];
            queueMaxSize = size;
            popIndex = 0;
            pushIndex = 0;
            queueCurSize = 0;
        }

        public int pop(){
            if (queueCurSize == 0){
                throw new RuntimeException("当前队列为空，无法取值");
            }
            queueCurSize--;
            int res = array[popIndex];
            popIndex = addIndex(popIndex);
            return res;
        }

        public void push(int value){
            if (queueCurSize == queueMaxSize){
                throw new RuntimeException("当前队列已满，无法插入新值");
            }
            queueCurSize++;
            array[pushIndex] = value;
            pushIndex = addIndex(pushIndex);
        }

        public void print(){
            for (int i : array) {
                System.out.print(i + " ");
            }
        }

        private int addIndex(int index) {
            if (index + 1 >= queueMaxSize){
                return 0;
            }
            return index + 1;
        }
    }
}
